package com.example.ui.contact.chat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.service.MainService;
import com.example.ui.Userdata;
import com.example.ui.contact.MsgState;
import com.example.ui.contact.adapter.ChatMsgViewAdapter;
import com.example.ui.contact.bean.ChatMsgItem;
import com.example.ui.contact.bean.MessageItem;
import com.example.ui.contact.bean.NoticeItem;
import com.example.ui.contact.bean.User;
import com.example.ui.contact.db.ChatMsgDB;
import com.example.ui.contact.db.MessageDB;
import com.example.ui.contact.face.CirclePageIndicator;
import com.example.ui.contact.face.FaceAdapter;
import com.example.ui.contact.face.FacePageAdeapter;
import com.example.ui.contact.face.FaceUtil;
import com.example.ui.contact.face.FaceViewPager;
import com.example.ui.contact.face.FaceViewPager.TransitionEffect;
import com.example.ui.contact.xlistview.MsgListView;
import com.example.ui.contact.xlistview.MsgListView.IXListViewListener;
import com.example.util.TimeUtil;
import com.example.util.Util;




public class ChatActivity extends Activity implements
		PushMessageReceiver.EventHandler,IXListViewListener{
	private InputMethodManager imm;
	public static final int NEW_MESSAGE = 0x001;// 收到消息

	private int currentPage = 0;
	private boolean isFaceShow = false;
	private Button sendBtn;
	private Button faceBtn;
	private EditText msgEt;
	private Button titleLeftBtn,titleRightBtn;
	private TextView titleText;
	private ChatMsgViewAdapter mAdapter;
	private FaceViewPager faceViewPager;
	private List<MessageItem> mDataArrays = new ArrayList<MessageItem>();
	private List<ChatMsgItem> msgList = new ArrayList<ChatMsgItem>();// 消息对象数组
	private ChatMsgDB chatMsgDB;
	
	//private ListView msgListView;	
	private MsgListView mMsgListView;
	
	private List<String> keys;
	private LinearLayout faceLinearLayout;
	
	
   
    private SharePreferenceUtil ownUser;
	private MessageDB mMsgDB;
    private String ownName = "自己";
	private String formUserId = "123456"; //好友id,不是百度的userid,而是注册应用分配的id
	private String formName = "Leone";
	private User mFromUser;
	private static int MsgPagerNum;
	HSApplication application = HSApplication.getInstance();
//	private Userdata userdata;
	/**
	 * 处理接收过来的消息
	 */
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			
			if (msg.what == NEW_MESSAGE) {
				String message = (String) msg.obj;
				if (message.length() > 0)
				{
					
					String MeContent;
					try {
						MeContent = new JSONObject(message.toString()).getString("msg");
						JSONObject json = new JSONObject(MeContent);
						ChatMsgItem item = new ChatMsgItem();	
						String content = json.getString("content");
						String time = json.getString("time");
						String name = json.getString("name");
						String id = json.getString("userid");
						item.setContent(content);
						item.setTime(time);
						item.setName(name);
						item.setUserid(id);
						if(json.optBoolean("pic")){
							item.setPic(json.getString("pic"));						
						}
						item.setComMeg(true);
						mAdapter.upDateMsg(item);
						//chatMsgDB.saveChatMsg(id,item);
						
					} catch (JSONException e) {
						e.printStackTrace();
						L.Debug("chat 接收 error", e.getMessage());
					}

				}		
				

			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_main);
		formName = getIntent().getStringExtra("mName");
		formUserId = getIntent().getStringExtra("mUserId");
		if(formName == null){formName ="Leone ..";}
		L.Debug("formName", ""+formName);
		L.Debug("formUserId", ""+formUserId);
		//if(formUserId.equals("")||formUserId==null){formUserId="6666";}	
		
		
		MsgState.state = MsgState.CHAT_MSG_STATE;

        ownUser = HSApplication.getInstance().getSpUtil();
        ownName =ownUser.getNick();
		findView();		
		initData();	
		//初始化表情设置
		initFacePage();


	}
    public void initData()
    {
		//		mFromUser = (User) getIntent().getSerializableExtra("user");
		//		if (mFromUser == null) {// 如果为空，直接关闭
		//			finish();
		//		}
    	
        initChatMsgData();      
    	mAdapter = new ChatMsgViewAdapter(this, msgList);
		//msgListView.setAdapter(mAdapter);
		//msgListView.setSelection(msgListView.getCount() - 1);
		
		mMsgListView = (MsgListView) findViewById(R.id.listview);
		// 触摸ListView隐藏表情和输入法
		//mMsgListView.setOnTouchListener(this);
		mMsgListView.setPullLoadEnable(false);
		mMsgListView.setXListViewListener(this);
		mMsgListView.setAdapter(mAdapter);
		mMsgListView.setSelection(mAdapter.getCount() - 1);
		
    }

	private void initFacePage() {
		Set<String> keySet = HSApplication.getInstance().getFaceMap()
				.keySet();
		keys = new ArrayList<String>();
		keys.addAll(keySet);
		
		List<View> lv = new ArrayList<View>();
		for (int i = 0; i < HSApplication.NUM_PAGE; ++i)
			lv.add(getGridView(i));
		FacePageAdeapter adapter = new FacePageAdeapter(lv, faceViewPager);
		faceViewPager.setAdapter(adapter);
		faceViewPager.setCurrentItem(currentPage);
		faceViewPager.setTransitionEffect(TransitionEffect.CubeOut);
		CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator);
		indicator.setViewPager(faceViewPager);		
		adapter.notifyDataSetChanged();
		faceLinearLayout.setVisibility(View.GONE);
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				currentPage = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// do nothing
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// do nothing
			}
		});
		adapter.notifyDataSetChanged();
		//faceLinearLayout.setVisibility(View.GONE);
		


	}
	private GridView getGridView(int i) {
		GridView gv = new GridView(this);
		gv.setNumColumns(7);
		gv.setSelector(new ColorDrawable(Color.TRANSPARENT));// 屏蔽GridView默认点击效果
		gv.setBackgroundColor(Color.TRANSPARENT);
		gv.setCacheColorHint(Color.TRANSPARENT);
		gv.setHorizontalSpacing(1);
		gv.setVerticalSpacing(1);
		gv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		gv.setGravity(Gravity.CENTER);
		gv.setAdapter(new FaceAdapter(this, i));
		gv.setOnTouchListener(forbidenScroll());
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == HSApplication.NUM) {// 删除键的位置
					int selection = msgEt.getSelectionStart();
					String text = msgEt.getText().toString();
					if (selection > 0) {
						String text2 = text.substring(selection - 1);
						if ("'".equals(text2)) {
							int start = text.lastIndexOf("'");
							int end = selection;
							msgEt.getText().delete(start, end);
							return;
						}
						msgEt.getText().delete(selection - 1, selection);
					}
				} else {
					int count = currentPage * HSApplication.NUM + arg2;
                    //****在EditText中显示文本*****
					String ori = msgEt.getText().toString();
					int index = msgEt.getSelectionStart();
					StringBuilder stringBuilder = new StringBuilder(ori);
					stringBuilder.insert(index, keys.get(count));
					msgEt.setText(stringBuilder.toString());
					msgEt.setSelection(index + keys.get(count).length());
					
					//					//*******在EditText中显示表情******
					//					Bitmap bitmap = BitmapFactory.decodeResource(
					//							getResources(), (Integer) HSApplication
					//									.getInstance().getFaceMap().values()
					//									.toArray()[count]);
					//					if (bitmap != null) {
					//						int rawHeigh = bitmap.getHeight();
					//						int rawWidth = bitmap.getHeight();
					//						int newHeight = 40;
					//						int newWidth = 40;
					//						// 计算缩放因子
					//						float heightScale = ((float) newHeight) / rawHeigh;
					//						float widthScale = ((float) newWidth) / rawWidth;
					//						// 新建立矩阵
					//						Matrix matrix = new Matrix();
					//						matrix.postScale(heightScale, widthScale);
					//						// 设置图片的旋转角度
					//						// matrix.postRotate(-30);
					//						// 设置图片的倾斜
					//						// matrix.postSkew(0.1f, 0.1f);
					//						// 将图片大小压缩
					//						// 压缩后图片的宽和高以及kB大小均会变化
					//						Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0,
					//								rawWidth, rawHeigh, matrix, true);
					//						ImageSpan imageSpan = new ImageSpan(ChatActivity.this,
					//								newBitmap);
					//						String emojiStr = keys.get(count);
					//						SpannableString spannableString = new SpannableString(
					//								emojiStr);
					//						spannableString.setSpan(imageSpan,
					//								emojiStr.indexOf("'"),
					//								emojiStr.indexOf("'") + 1,
					//								Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					//						msgEt.append(spannableString);
					//					} else {
					//						String ori = msgEt.getText().toString();
					//						int index = msgEt.getSelectionStart();
					//						StringBuilder stringBuilder = new StringBuilder(ori);
					//						stringBuilder.insert(index, keys.get(count));
					//						msgEt.setText(stringBuilder.toString());
					//						msgEt.setSelection(index + keys.get(count).length());
					//					}
				}
			}
		});
		return gv;
	}   
    
//	/**
//	 * 加载消息历史，从数据库中读出
//	 */
//	private List<MessageItem> initMsgData() {
//		List<MessageItem> list = mMsgDB.getMsg(formUserId,0);  //getMsg(mFromUser.getUserId(),MsgPagerNum);
//		List<MessageItem> msgList = new ArrayList<MessageItem>();// 消息对象数组
//		if (list.size() > 0) {
//			for (MessageItem entity : list) {
//				if (entity.getName().equals("")) {
//					entity.setName(formUserId);  //mFromUser.getNick()
//				}
//
//				msgList.add(entity);
//			}
//		}
//		return msgList;
//
//	}
	
	
	/**
	 * 从数据库中读出私信消息数据
	 */
	public void initChatMsgData() {
		 chatMsgDB = HSApplication.getInstance().getChatMsgDB();
		List<ChatMsgItem> list = chatMsgDB.getChatMsgList(formUserId,MsgPagerNum);  //getMsg(mFromUser.getUserId(),MsgPagerNum);
		msgList.clear();
		if (list.size() > 0) {
			for (ChatMsgItem entity : list) {

				msgList.add(entity);
			}
		}

	}
	
	private void findView() {

		
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		
    	//msgListView = (ListView) findViewById(R.id.listview);
		titleLeftBtn = (Button)findViewById(R.id.layout_title_left_btn);
		titleRightBtn= (Button)findViewById(R.id.layout_title_right_btn);
		titleText=(TextView)findViewById(R.id.layout_title_middle_text);
		sendBtn = (Button)findViewById(R.id.btn_send);
		faceBtn = (Button)findViewById(R.id.btn_face);
		msgEt = (EditText) findViewById(R.id.et_sendmessage);
		faceLinearLayout = (LinearLayout) findViewById(R.id.face_ll);
		faceViewPager = (FaceViewPager) findViewById(R.id.face_pager);
		titleLeftBtn.setText("返回");
		titleText.setText(formName);
		titleRightBtn.setVisibility(View.INVISIBLE);
		titleLeftBtn.setClickable(true);
		titleLeftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Util.toast(ChatActivity.this, "onClick 确定");
				finish();
			}
		});	
		
		// 触摸ListView隐藏表情和输入法
			//		msgListView.setOnTouchListener(new OnTouchListener() {
			//
			//			@Override
			//			public boolean onTouch(View v, MotionEvent event) {
			//				imm.hideSoftInputFromWindow(msgEt.getWindowToken(), 0);
			//				faceLinearLayout.setVisibility(View.GONE);
			//				isFaceShow = false;
			//				return false;
			//			}
			//		});
		
		//发送消息监听
		sendBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Util.toast(ChatActivity.this, "onClick sendBtn");
				send();
				//if (NetUtil.isNetConnected(HSApplication.getInstance())) {//如果网络可用
				//	send();
				//} else {
				//	T.showLong(HSApplication.getInstance(), R.string.net_error_tip);
				//}				
			
			}
		});	
		
		//表情按钮监听
		faceBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!isFaceShow) {
					imm.hideSoftInputFromWindow(msgEt.getWindowToken(), 0);
					try {
						Thread.sleep(80);// 解决此时会黑一下屏幕的问题
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					faceLinearLayout.setVisibility(View.VISIBLE);
					isFaceShow = true;
				} else {
					faceLinearLayout.setVisibility(View.GONE);
					isFaceShow = false;
				}	
				L.Debug("faceBtn", "run");

			}
		});
		
    }
	public void send()
	{
		String msg = msgEt.getText().toString();
		if (msg.length() > 0)
		{   String ownId = HSApplication.sp.getString("userid","");
		    String ownName = HSApplication.sp.getString("username","");
			ChatMsgItem entity = new ChatMsgItem();
			entity.setTime(TimeUtil.getTime(System.currentTimeMillis()));//System.currentTimeMillis()
			entity.setName(ownName);
			entity.setComMeg(false);
			entity.setContent(msg);
			entity.setUserid(ownId);
			
			//			mDataArrays.add(entity); id(userdata.getUserId()
			//			mAdapter.notifyDataSetChanged();
			
			//消息本地保存
			//mMsgDB.saveMsg(formUserId, entity);
			L.Debug("ownId", ownId);
			chatMsgDB.saveChatMsg(formUserId,entity);
			mAdapter.upDateMsg(entity);	

			msgEt.setText("");
			//msgListView.setSelection(msgListView.getCount() - 1);			
			mMsgListView.setSelection(mAdapter.getCount() - 1);
			
			//new SendMsgAsyncTask(msg, "000").send();
			new SendMsgAsyncTask(msg,ownId,formUserId).send();
		}
	}

   private String getDate() {
        Calendar c = Calendar.getInstance();

        String year = String.valueOf(c.get(Calendar.YEAR));
        String month = String.valueOf(c.get(Calendar.MONTH));
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(c.get(Calendar.MINUTE));
        
        
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); 
        						
        						
        return sbBuffer.toString();
    }	

	// 防止乱pageview乱滚动
	private OnTouchListener forbidenScroll() {
		return new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					return true;
				}
				return false;
			}

		};
	}	

   
	@Override
	protected void onResume() {
		super.onResume();
		//		application.getNotificationManager().cancel(
		//				PushMessageReceiver.NOTIFY_ID);
		PushMessageReceiver.ehList_Chat.add(this);// 监听推送的消息
	}

	@Override
	protected void onPause() {
		imm.hideSoftInputFromWindow(msgEt.getWindowToken(), 0);
		faceLinearLayout.setVisibility(View.GONE);
		isFaceShow = false;		
		super.onPause();
		PushMessageReceiver.ehList_Chat.remove(this);// 监听推送的消息

	}


	@Override
	public void onMessage(String message) {
		
		L.Debug("ChatActivity msg", message);
		Message handlerMsg = handler.obtainMessage(NEW_MESSAGE);
		handlerMsg.obj = message;
		handler.sendMessage(handlerMsg);		
	}


	@Override
	public void onBind(String method, int errorCode, String content) {
		
	}


	@Override
	public void onNotify(String title, String content) {
		
	}


	@Override
	public void onNetChange(boolean isNetConnected) {
		
	}
	@Override
	public void onRefresh() {
		MsgPagerNum++;
		//List<MessageItem> msgList = initMsgData();
		initChatMsgData();
		int position = mAdapter.getCount();
		mAdapter.setMsgList(msgList);
		mMsgListView.stopRefresh();
		mMsgListView.setSelection(mAdapter.getCount() - position - 1);
		L.i("MsgPagerNum = " + MsgPagerNum + ", adapter.getCount() = "
				+ mAdapter.getCount());		
	}
	@Override
	public void onLoadMore() {
		
	}

	
}





